import {
  getGame,
  addClick,
  addOpen
} from "../../api/getApi"


Page({

  /**
   * 页面的初始数据
   */
  data: {
    searchText:"",
    gameData: [],
    cainiGame:[],
    historyData: wx.getStorageSync('historyData')?JSON.parse(wx.getStorageSync('historyData')):[],
    isClick:false,
    page:1,
    limit:25
  },
  onSearch(e){
    this.setData({gameData:[],page:1,isClick:true})
    let historyData = wx.getStorageSync('historyData')?JSON.parse(wx.getStorageSync('historyData')):[]
    if(!historyData.find(v=>v===this.data.searchText)&&this.data.searchText.length>0){
      historyData=[this.data.searchText,...historyData]
      wx.setStorageSync('historyData', JSON.stringify(historyData))
      this.setData({historyData:historyData})
    }
    if(this.data.searchText.length>0){
      this.getData()      
    }
  },
  onChange(e) {
    console.log(e)
    this.setData({
      searchText: e.detail.value,
    });
    if(!this.data.searchText || this.data.searchText.length==0){
      this.setData({
        isClick: false,
        page:1,
        gameData:[],
      });
    }
  },
  down(e) {
    this.setData({page:this.data.page+1})
    this.getData() 
  },
  getData() {
    getGame({
      page: this.data.page,
      limit: this.data.limit,
      appname:this.data.searchText,
      briefIntro:this.data.searchText,
      searchAll:"true",
    }).then(res => {
      const list = res.list;
      if (list && list.length > 0) {
        const resultList = list.map(item => {
          const appnameHighlighted = this.highlightText(item.appname, this.data.searchText);
          const briefIntroHighlighted = this.highlightText(item.briefIntro, this.data.searchText);
          return {
           ...item,
            appname: appnameHighlighted,
            briefIntro: briefIntroHighlighted
          };
        });
        this.setData({
            gameData: [...this.data.gameData,...resultList]
        });
      }
    })
  },
  highlightText(text, keyword) {
    if (!keyword) {
      return text;
    }
    const reg = new RegExp(keyword, 'gi');
    return text.replace(reg, `<span class="highlight">${keyword}</span>`);
  },
  goToGame(e){
    let itemdata = e.currentTarget.dataset.data
    if (itemdata.appid){
      wx.navigateToMiniProgram({
        appId: itemdata.appid, 
        path: '?wxgamepro=CpsCBgAAoXkpQY9UXS9__OwV',
        envVersion: 'release',
        success:(res)=>{
          let myGame = wx.getStorageSync('myGame')
          if(!myGame){
            myGame = []
          }else{
            myGame = JSON.parse(myGame).slice(0, 300)
          }
          if(!myGame.find(v=>v.id===itemdata.id)){
            myGame=[itemdata,...myGame]
          }
          wx.setStorageSync('myGame', JSON.stringify(myGame))
          this.setData({myGame:myGame})
          addOpen({id:itemdata.id})
        }
      })
      addClick({id:itemdata.id})
    }else{
      wx.showToast({
        title: `尊敬的大人对对不不起起！此游戏出了点小问题~`,
        icon: 'none',
      });
    }
  },

  //点击立即搜索
  fastSearch(e){
    this.setData({gameData:[],page:1,isClick:true,searchText:e.currentTarget.dataset.data})
    let historyData = wx.getStorageSync('historyData')?JSON.parse(wx.getStorageSync('historyData')):[]
    if(!historyData.find(v=>v===this.data.searchText)){
      historyData=[this.data.searchText,...historyData]
      wx.setStorageSync('historyData', JSON.stringify(historyData))
      this.setData({historyData:historyData})
    }
    if(this.data.searchText.length>0){
      this.getData()      
    }
  },

  getRandomGame(){
    getGame({page:1,limit:10,randomGame:'true'}).then(res => {
      this.setData({cainiGame:res.list})
    })
  },

  deleteHistory(){
    let data =[]
    wx.setStorageSync('historyData', JSON.stringify(data))
    this.setData({historyData:[]})
  },

  onLoad(options) {
    this.getRandomGame()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.setData({historyData:wx.getStorageSync('historyData')?JSON.parse(wx.getStorageSync('historyData')):[]})
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  }
})